<script lang="ts" setup>
import type { Issue } from '#/api';

import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, InputSearch } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenForm } from '#/adapter/form';
import { addIssue, updateIssue } from '#/api';

import { useSchema } from './data';
import MaterialTableGrid from './modules/materialtable.vue';
import SearchWorkorderModal from './modules/workordermodal.vue';
import SearchWorkstationModal from './modules/workstationmodal.vue';

const emit = defineEmits(['success']);
const formData = ref<Issue.Row>();
const title = ref<string>();
const workorder = ref<string>();
const workstation = ref<string>();
const workstationName = ref<string>();
const clientCode = ref<string>();
const clientName = ref<string>();
const showConfrimBtn = ref(true);
// 是否显示物料表格
const showMaterialTable = ref(false);
const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid grid-cols-12',
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: useSchema(),
  showDefaultActions: false,
});

const getTitle = computed(() => {
  if (formData.value?.attr1 === '1') return '查看生产领料信息';
  return formData.value?.attr1 === '2'
    ? '编辑生产领料信息'
    : '新增生产领料信息';
});
watch(getTitle, (newTitle) => {
  title.value = newTitle;
});
const [Modal, modalApi] = useVbenModal({
  class: 'w-[800px]',
  closeOnClickModal: false,
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();

      let data;
      await formApi.getValues().then((res) => {
        data = res;
        data.requiredTime = dayjs(data.requiredTime).format(
          'YYYY-MM-DD HH:mm:ss',
        );
      });
      try {
        await (formData.value?.issueId ? updateIssue(data!) : addIssue(data!));
        modalApi.close();
        emit('success');
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<Issue.Row>();
      if (data) {
        // 回显格式化日期
        data.requiredTime = dayjs(data.requiredTime) as any;
        formData.value = data;
        showMaterialTable.value = !!data.issueId;
        workorder.value = formData.value.workorderCode;
        clientCode.value = formData.value.clientCode;
        clientName.value = formData.value.clientName;
        workstation.value = formData.value.workstationCode!;
        workstationName.value = formData.value.workstationName!;
        formApi.setValues(formData.value);
        showConfrimBtn.value = formData.value?.attr1 !== '1';
        modalApi.setState({
          showConfirmButton: showConfrimBtn.value,
        });
      }
    }
  },
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues({});
}
// 点击提交更改单据状态
function changeStatus() {
  let status = 'APPROVING';
  const currentStatus = formData.value?.status;
  if (currentStatus === 'PREPARE') {
    status = 'APPROVING';
  } else if (currentStatus === 'APPROVING') {
    status = 'APPROVED';
  }
  formApi.setFieldValue('status', status);
  modalApi.onConfirm();
}

// 生产工单搜索子弹框
const [WorkorderModal, workorderModalApi] = useVbenModal({
  connectedComponent: SearchWorkorderModal,
  // 确认关闭或取消子弹框后回显数据
  onClosed() {
    workorder.value = workorderModalApi.getData().workorderCode;
    formApi.setFieldValue(
      'workorderId',
      workorderModalApi.getData().workorderId,
    );
    formApi.setFieldValue(
      'workorderCode',
      workorderModalApi.getData().workorderCode,
    );
    formApi.setFieldValue('clientId', workorderModalApi.getData().clientId);
    formApi.setFieldValue('clientCode', workorderModalApi.getData().clientCode);
    formApi.setFieldValue('clientName', workorderModalApi.getData().clientName);
  },
});

// 工作站搜索子弹框
const [WorkstationModal, workstationModalApi] = useVbenModal({
  connectedComponent: SearchWorkstationModal,
  // 确认关闭或取消子弹框后回显数据
  onClosed() {
    workstation.value = workstationModalApi.getData().workstationCode;
    formApi.setFieldValue(
      'workstationId',
      workstationModalApi.getData().workstationId,
    );
    formApi.setFieldValue(
      'workstationCode',
      workstationModalApi.getData().workstationCode,
    );
    formApi.setFieldValue(
      'workstationName',
      workstationModalApi.getData().workstationName,
    );
  },
});
</script>

<template>
  <Modal :title="getTitle" :show-confirm-button="false">
    <Form class="mx-4">
      <template #workorderCode>
        <InputSearch
          placeholder="请选择生产工单"
          @search="workorderModalApi.open()"
          v-model:value="workorder"
          readonly
        />
      </template>
      <template #workstationCode>
        <InputSearch
          placeholder="请选择工作站"
          @search="workstationModalApi.open()"
          v-model:value="workstation"
          readonly
        />
      </template>
    </Form>
    <div v-if="showMaterialTable">
      <MaterialTableGrid
        :id="formData?.issueId!"
        :status="formData?.status!"
        :attr1="formData?.attr1 as any"
      />
    </div>
    <template #prepend-footer>
      <div
        class="flex flex-auto justify-between"
        v-if="
          (showConfrimBtn && formData?.status === 'PREPARE') || !formData?.attr1
        "
      >
        <div>
          <Button type="primary" danger @click="resetForm"> 重置 </Button>
        </div>
        <div class="flex gap-2">
          <Button
            type="primary"
            class="bg-[#67c23a] hover:!bg-[#a3db87]"
            @click="modalApi.onConfirm"
          >
            保存
          </Button>

          <Button type="primary" @click="changeStatus" v-if="formData?.attr1">
            提交
          </Button>
        </div>
      </div>
    </template>
  </Modal>
  <WorkorderModal />
  <WorkstationModal />
</template>
